<?php


namespace api\app\controller;


use api\app\model\AddressModel;
use api\app\model\GoodsModel;
use api\app\model\OrderModel;
use api\app\model\UserModel;
use cmf\controller\RestBaseController;
use think\Request;

class OrderController extends RestBaseController
{
    //创建订单
    public function createOrder(Request $request)
    {
        //接收数据
        $data = input('post.');
        //查询出商品
        $goodsInfo = GoodsModel::find($data['goods_id']);
        //商品的规格
        $dataInfo = $data['goods_info'];

        //单价
        $price = $this->goodsPrice($goodsInfo,$dataInfo);
        if (empty($price)){
            $this->error('错误');
        }
//        //定义单价
//        $price = null;
//        //循环判断出商品规格
//        foreach (json_decode($goodsInfo['info'],true) as $value) {
//            if ($value['颜色'] == $dataInfo['颜色'] && $value['型号'] == $dataInfo['型号']) {
//                $price = $value['价格'];
//            }else{
//                $this->error('该商品无');
//            }
//        }
        //查询商品列表
        $goods = GoodsModel::find($data['goods_id']);
        if (!$goods) {
            $this->error('商品不存在');
        }
        if ($goods['switch'] != 1) {
            $this->error('商品缺货或下架');
        }
        //查询收货地址列表
        $address = AddressModel::find($data['address_id']);
        if (!$address) {
            $this->error('收货地址不存在');
        }
        //
        $add_data = [
            'user_id' =>$request->token,
            'goods_name' => $goods['name'],
            'goods_info' => json_encode($data['goods_info']),
            'price' => $price['价格'],
            'num' => $data['num'],
            'total_price' => $price['价格'] * $data['num'],
            'trade_no' => date('YmdHis') . mt_rand(1111,9999),
            'user_name' =>$address['name'],
            'user_mob' => $address['mobile'],
            'user_address' => $address['ssq'] . $address['address'],
            'pay_type' => $data['pay_type'],
            'switch' => 0,
            'remarks' => $data['remarks'],
            'create_time' => date('Y-m-d H:i:s'),
        ];
        $model = new OrderModel();
        if ($model->save($add_data)){
           $this->success('创建订单成功',[
               'payInfo' => [
                   'order_id' =>$model->id
               ]
           ]);
        }else {
            $this->error('创建订单失败');
        }
    }
    //单价查询
    private function goodsPrice($goods,$dataInfo)
    {
       $goodsInfo = json_decode($goods['info'],true);
        foreach ($goodsInfo as $value) {
            $sku = true;
            foreach ($dataInfo as $key => $val) {
                if ($value[$key] != $val) {
                    $sku = false;
                }
            }
            if ($sku) {
                return $value ;
            }else{
               continue;
            }
        }



    }

}